package com.mengchengnet.chaperonage.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.util.OrderInfoUtil2_0;
import com.mengchengnet.chaperonage.util.PayResult;
import com.mengchengnet.chaperonage.wxapi.WXPayEntryActivity;

import java.util.Map;

import static com.mengchengnet.chaperonage.ui.activity.OrderActivity.RSA2_PRIVATE;
import static com.mengchengnet.chaperonage.ui.activity.OrderActivity.RSA_PRIVATE;

/**
 * Created by Administrator on 2017/9/25.
 */

public class ALiPayResult extends BaseActivity{
    private Button btn;
    private TextView tv;
    private ImageView iv;
    String IsSucess;//支付宝支付是否成功
    private static final int SDK_PAY_FLAG = 1;
    private static final String APPID="2017082408349943";
    private static final String TAG = "ALiPayResult";
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ALiPayResult.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent =new Intent(ALiPayResult.this, WXPayEntryActivity.class);
                        intent.putExtra("isSucess","0");
                        startActivity(intent);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ALiPayResult.this, "支付失败", Toast.LENGTH_SHORT).show();
                        Intent intent =new Intent(ALiPayResult.this, WXPayEntryActivity.class);
                        intent.putExtra("isSucess","1");
                        startActivity(intent);
                    }
                    break;
                }


            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_result);
        toolbarState=TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("支付结果");
        btn= (Button) findViewById(R.id.result_btn);
        tv= (TextView) findViewById(R.id.result_tv);
        iv= (ImageView) findViewById(R.id.result_imageview);
        Intent intent =getIntent();
        IsSucess=intent.getStringExtra("isSucess");
    }

    @Override
    protected void onResume() {
        super.onResume();
        		if (IsSucess.equals("0")){
			btn.setText("查看订单详情");
			tv.setText("支付成功");
			iv.setImageResource(R.mipmap.pay_sucess);
			btn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent=new Intent(ALiPayResult.this, MyOrderActivity.class);
					intent.putExtra("kkey","1");
					startActivity(intent);
				}
			});
		}else if(IsSucess.equals("1")){
			btn.setText("重新付款");
			tv.setText("支付失败");
			iv.setImageResource(R.mipmap.pay_failed);
			btn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					payV2();
				}
			});
		}
    }


    /**
     * 支付宝支付业务
     *
     * @param
     */
    public void payV2() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ALiPayResult.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
